<script setup lang="ts">
  import { addPatientApi, patientDetailApi, updatePatientApi } from '@/apis/patient'
  import { ref } from 'vue'

  const formData = ref({
    name: '',
    idCard: '',
    gender: 1,
    defaultFlag: 1,
  })

  const onSwichChange = (event: UniHelper.SwitchOnChangeEvent) => {
    formData.value.defaultFlag = event.detail.value ? 1 : 0
  }

  //  defineProps
  //     页面 -  获取页面参数
  //     组件 -  获取父传子的参数
  const pageParams = defineProps<{ id: string }>()

  const getDetail = async () => {
    const res = await patientDetailApi(pageParams.id)
    formData.value = {
      name: res.name,
      idCard: res.idCard,
      gender: res.gender || 0,
      defaultFlag: res.defaultFlag,
    }
  }

  if (pageParams.id) {
    uni.setNavigationBarTitle({ title: '编辑患者' })
    getDetail()
  }

  const form = ref<UniHelper.UniFormsInstance>()

  const formRules: UniHelper.UniFormsRules = {
    name: {
      rules: [
        { required: true, errorMessage: '请填写姓名' },
        { pattern: /^[\u4e00-\u9fa5]{2,4}$/, errorMessage: '请输入正确的姓名' },
      ],
    },
    idCard: {
      rules: [
        { required: true, errorMessage: '请填写身份证号' },
        {
          pattern:
            /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
          errorMessage: '请输入正确的身份证号',
        },
      ],
    },
    gender: {
      rules: [
        { required: true, errorMessage: '请选择性别' },
        {
          validateFunction: (rule, value, data, callback) => {
            if (Number(formData.value.idCard.charAt(16)) % 2 !== value) {
              callback('身份证号与性别不匹配')
            }
            return true
          },
        },
      ],
    },
  }

  const onSubmit = async () => {
    try {
      await form.value?.validate?.()
      // 判断是否有 id
      if (pageParams.id) {
        // 修改患者信息
        await updatePatientApi({
          ...formData.value,
          id: pageParams.id,
        })
      } else {
        // 提交表单数据给服务器，添加患者信息
        await addPatientApi(formData.value)
      }
      uni.showToast({ title: '保存成功', icon: 'success' })
      // 跳转到患者列表页面
      uni.navigateBack()
    } catch (error) {
      console.log(error)
    }
  }
</script>

<template>
  <scroll-page>
    <view class="archive-page">
      <uni-forms border label-width="220rpx" ref="form" :rules="formRules" :model="formData">
        <uni-forms-item label="患者姓名" name="name">
          <uni-easyinput
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :styles="{ color: '#121826' }"
            :input-border="false"
            :clearable="false"
            placeholder="请填写真实姓名"
            v-model="formData.name"
          />
        </uni-forms-item>
        <uni-forms-item label="患者身份证号" name="idCard">
          <uni-easyinput
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :styles="{ color: '#121826' }"
            :input-border="false"
            :clearable="false"
            placeholder="请填写身份证号"
            v-model="formData.idCard"
          />
        </uni-forms-item>
        <uni-forms-item label="患者性别" name="gender">
          <uni-data-checkbox
            v-model="formData.gender"
            selectedColor="#16C2A3"
            :localdata="[
              { text: '男', value: 1 },
              { text: '女', value: 0 },
            ]"
          />
        </uni-forms-item>
        <uni-forms-item label="默认就诊人" name="defaultFlag">
          <view class="uni-switch">
            <switch
              @change="onSwichChange"
              :checked="formData.defaultFlag === 1"
              color="#20c6b2"
              style="transform: scale(0.7)"
            />
          </view>
        </uni-forms-item>
        <text>{{ formData }}</text>
        <button class="uni-button" @click="onSubmit">保存</button>
      </uni-forms>
    </view>
  </scroll-page>
</template>

<style lang="scss">
  @import './index.scss';
</style>
